package model.backoffice

import scala.util.matching.Regex
import scala.util.{Try, Success, Failure}

case class BackofficeParams(
    offset: Int,
    startPeriod: Long,
    filter: String,
    limit: Int
)

object BackofficeParams {
  private val defaultLimit: Int     = 100
  private val defaultPeriod: Long   = 1717200000 // 01.06.2024
  private val defaultOffset: Int    = 0
  private val defaultFilter: String = ""

  private def convert[A: StringConverter](input: String): Option[A] = {
    Try(implicitly[StringConverter[A]].convert(input)) match {
      case Success(value) => Some(value)
      case Failure(_)     => None
    }
  }

  private def validateParam[A: StringConverter](
      param: Option[String],
      condition: A => Boolean,
      defaultValue: A
  ): A = {
    val convertedParam: Option[A] = param match {
      case Some(value) => convert[A](value)
      case _           => None
    }
    val validatedParam = convertedParam match {
      case Some(value) if condition(value) => value
      case _                               => defaultValue
    }
    validatedParam
  }

  def validateParams(params: Map[String, Option[String]]): BackofficeParams = {
    val validatedOffset =
      validateParam[Int](params.getOrElse("offset", None), (x: Int) => x > 0, defaultOffset)

    val validatedPeriod = validateParam[Long](
      params.getOrElse("period", None),
      (x: Long) => x > defaultPeriod,
      defaultPeriod
    )
    val validatedLimit =
      validateParam[Int](params.getOrElse("limit", None), (x: Int) => x > 0, defaultLimit)

    val filterPattern: Regex = "^[a-zA-Zа-яА-ЯёЁ]+ [a-zA-Zа-яА-ЯёЁ]+$".r
    val filterFunction = (x: String) =>
      filterPattern.findFirstMatchIn(x) match
        case Some(_) => true
        case _       => false
    val validatedFilter =
      validateParam[String](params.getOrElse("filter", None), filterFunction, defaultFilter)

    BackofficeParams(
      offset = validatedOffset,
      startPeriod = validatedPeriod,
      filter = validatedFilter,
      limit = validatedLimit
    )
  }
}
